package com.ctshk.rpc.payment.utils.wechat;

import com.ctshk.common.utils.MD5Util;
import com.ctshk.rpc.payment.dto.WeChatPayConfig;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * @BelongsProject: ctshk-cloud
 * @BelongsPackage: com.ctshk.rpc.payment.utils.wechat
 * @Author: hef
 * @CreateTime: 2021-04-26 16:45
 * @Description: 描述
 */
public class WeChatPayUtil {

    private static final String SIGN = "sign";
    /**
     * 校验签名是否有效
     *
     * @param config
     * @param data
     * @return
     */
    public static boolean isSignatureValid(WeChatPayConfig config,
                                           Map<String, String> data) {
        if (!data.containsKey(SIGN)) {
            return false;
        }
        String sign = data.get(SIGN);
        String s = generateSignature(data, config.getMKey());
        return s.equals(sign);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data 待签名数据
     * @param key  API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key)  {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(SIGN)) {
                continue;
            }
            // 参数值为空，则不参与签名
            if (data.get(k).trim().length() > 0)
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        return MD5Util.stringMd5(sb.toString()).toUpperCase();
    }
}
